package com.base.myproject.client.HR.Salary;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.LabelField;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupSummaryView;
import com.extjs.gxt.ui.client.widget.grid.SummaryColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.SummaryRenderer;
import com.extjs.gxt.ui.client.widget.grid.SummaryType;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class Hr_hostel_amount extends BaseJDBCPanel{
	
	private Button btnQuery = null;
	private Button btnAdd = null;
	private DateField dfQuery = null;
	private DateField dfAdd = null;
	private NumberField nfMoney = null;
	private BaseComboBoxForm<BaseModelData> bcb= null;
	private BaseComboBoxForm<BaseModelData> bcb2= null;  
	private TextField<String> tfNum = null;
	private GroupingStore<BusiObject> store = null;
	private EditorGrid<BusiObject> grid=null;
	private NumberField hotelMoney = null;
	private DateField dfMake = null;
	private Button btnMake = null;
	private Button toExcel = new Button("导出到EXCEL");
	private String searchDate = "0";
	private String hostel = "0";
	private String type = "0";
	
	Label lab = new Label("宿舍号：");       //添加一个宿舍号标签
	TextField<String> tx = new TextField<String> ();   //定义一个文本框输入查询条件
	

	public Hr_hostel_amount(){
		init();
	}
	
	public void init(){
		toExcel.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				String data = "searchDate=" + searchDate + "&hostel=" + hostel + "&type=" + type;
				Window.open(GWT.getHostPageBaseURL() + "hr_Jsp/toHostelExcel.jsp?" + data,"_blank",null);
			}
		});
		
		initWidget();
	}
	
	public void complete() {
		super.complete();
		getToolbarll().add(toExcel);
	}
	
	private void initWidget(){
		btnQuery = new Button("查询");
		btnAdd = new Button("添加");
		btnMake = new Button("计算宿舍费用");
		hotelMoney = new NumberField();
		hotelMoney.setWidth(110);
		hotelMoney.setValue(-30);
		dfMake = new DateField();
		dfQuery = new DateField();                //Query time
		dfAdd = new DateField();                  //Add time
		nfMoney = new NumberField();              //money field
		bcb = new BaseComboBoxForm<BaseModelData>("code","desc_cn","hr_Salary_Item","where code='D02' ",true);
		bcb2 = new BaseComboBoxForm<BaseModelData>("code","desc_cn","hr_Salary_Item","where code='D02' or code='D01'",true);
		tfNum = new TextField<String>();          //hotel num
		
		costBox.setButtons("");
		costBox.setButtons(MessageBox.YESNO);  
		costBox.setIcon(MessageBox.QUESTION);  
		costBox.setTitle("是否生成数据？");  
		costBox.addCallback(new Listener<MessageBoxEvent> (){
			@Override
			public void handleEvent(MessageBoxEvent be) {
				if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
					String hostelcodestr =tfNum.getValue();
					String month = DateTimeFormat.getFormat("yyyy-MM").format(dfAdd.getValue());
					String delete = "delete hr_salary_ext where code='D02' and others = '" + hostelcodestr + "' and convert(varchar(7), adddate, 120)='"+month+"'";
					add(delete);
				}
			}
		});  
		costBox.setMessage("当前月份已生成该宿舍水电费，重新生成将清除老记录，您确认重新生成吗？是 则删除当月'系统生成'的再生成,否 则不做操作。");  
		
		initInnerToolBar();
	}
	
	private void initInnerToolBar(){
		HorizontalPanel hp1 = new HorizontalPanel();
		HorizontalPanel hp2 = new HorizontalPanel();
		HorizontalPanel hp3 = new HorizontalPanel();
		HorizontalPanel hp4 = new HorizontalPanel();
		VerticalPanel vpanel = new VerticalPanel();
		
		FieldSet fs = new FieldSet();
		fs.setHeading("查询操作");
		hp1.add(new LabelField("查询月份"));
		dfQuery.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM"));  
		dfQuery.setWidth(125);
		hp1.add(dfQuery);
		hp1.add(lab);
		tx.setWidth(125);
		hp1.add(tx);
		Label lab2 = new Label("费用类型："); 
		hp1.add(lab2);
	
		hp1.add(bcb2);
	
		
		hp1.add(btnQuery);
		hp1.add(new LabelField("　"));
		fs.add(hp1);
	    	
		FieldSet fs1 = new FieldSet();
		fs1.setHeading("添加宿舍住宿费");
		hp2.add(new LabelField("住宿费用"));
		hotelMoney.setWidth(70);
		hp2.add(hotelMoney);
		hp2.add(new LabelField("月份"));
		dfMake.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM"));
		dfMake.setWidth(100);
		hp2.add(dfMake);
		hp2.add(btnMake);
	
		fs1.add(hp2);
       
		
		FieldSet fs2 = new FieldSet();
		fs2.setHeading("添加宿舍水电费");

		hp3.add(new LabelField("日期"));
		dfAdd.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		dfAdd.setWidth(100);
		hp3.add(dfAdd);
		
		hp3.add(new LabelField("费用类型"));
		bcb.setWidth(100);
		hp3.add(bcb);
		
		hp3.add(new LabelField("宿舍编号"));
		tfNum.setWidth(70);
		hp3.add(tfNum);
		
		hp3.add(new LabelField("金额"));
		nfMoney.setWidth(70);
		nfMoney.setPropertyEditorType(Double.class);
		hp3.add(nfMoney);
		
		hp3.add(btnAdd);
		fs2.add(hp3);
		
		hp4.add(fs1);
		hp4.setSpacing(3);
		hp4.add(fs2);
		vpanel.add(fs);
		vpanel.add(hp4);

	
		btnAdd.addListener(Events.Select, getListener());
		btnMake.addListener(Events.Select, getListener());
		tfNum.addListener(Events.Change, getListener());
		nfMoney.addListener(Events.KeyPress, getListener());
		btnQuery.addListener(Events.Select, getListener());
		
		
		vpanel.setSpacing(3);
		
		vpanel.add(createGrid());
    	this.setLayout(new FitLayout());
		this.add(vpanel);
	}
	
	GroupingStore<BusiObject> getGroupStore() {
		if (store == null) {
			createGroupStore();
		}
		return store;
	}

	GroupingStore<BusiObject> createGroupStore() {
		store = new GroupingStore<BusiObject>();
		String sql = "select  icode,code,ROUND(amount,2) as amount,adddate,bcode,createdate,createbcode,others  from hr_salary_ext where 1=2";
		store.groupBy("others");
		getEmployeeChange(sql);
		return store;
	}
	
	private void getEmployeeChange(String sql) {
		final GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(sql, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				getGroupStore().removeAll();
				if (result.getRowCount() > 0) {
					BusiObject bo = null;
					List<BusiObject> list = new ArrayList<BusiObject>();
					for(int i=0; i<result.getRowCount(); i++) {
						bo = new BusiObject();
						bo.set("adddate", result.getValue(i, "adddate").substring(0,10));
						bo.set("others", "宿舍编号："+result.getValue(i, "others"));
						bo.set("code", result.getValue(i, "code"));
						bo.set("bcode", result.getValue(i, "bcode"));
						bo.set("amount", result.getValue(i, "amount"));
						bo.set("createdate", result.getValue(i, "createdate"));
						list.add(bo);
					}
					getGroupStore().add(list);
					grid.getView().refresh(true);
				}
			}
		});
	}
	
	private Grid<BusiObject> createGrid(){
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();  
	
		SummaryColumnConfig<Double> C3 = new SummaryColumnConfig<Double>("adddate", "发生日期", 30);
		C3.setSummaryRenderer(new SummaryRenderer() {  
		    public String render(Number value, Map<String, Number> data) {  
		         return "合计";  
		    }  
		});  
		columns.add(C3);
		SummaryColumnConfig<Double> C5 = new SummaryColumnConfig<Double>("code", "费用类型",30);
		BaseComboBoxForm<BaseModelData> bsb3 = new BaseComboBoxForm<BaseModelData>("code","desc_cn","hr_Salary_Item","",true);
		C5.setRenderer(bsb3);
		columns.add(C5);
		SummaryColumnConfig<Double> C6 = new SummaryColumnConfig<Double>("bcode", "雇佣编号", 30);
		BaseComboBoxForm<BaseModelData> bsb2 = new BaseComboBoxForm<BaseModelData>("bcode","employno","v_bcode2job","",true);
		C6.setRenderer(bsb2);
		columns.add(C6);
		
		SummaryColumnConfig<Double> C10 = new SummaryColumnConfig<Double>("bcode", "雇员姓名", 30);
		BaseComboBoxForm<BaseModelData> bsb4 = new BaseComboBoxForm<BaseModelData>("bcode","bname","v_bcode2job","",true);
		C10.setRenderer(bsb4);
		columns.add(C10);
		
		 SummaryColumnConfig<Double> C7 = new SummaryColumnConfig<Double>("createdate", "添加日期", 40);
		 columns.add(C7);
		
	    SummaryColumnConfig<Double> estimate = new SummaryColumnConfig<Double>("amount", "金额", 30);  
	    estimate.setRenderer(new GridCellRenderer<BusiObject>() {  
	        public String render(BusiObject model, String property, ColumnData config, int rowIndex, int colIndex,  
	            ListStore<BusiObject> store, Grid<BusiObject> grid) {  
	            return NumberFormat.getCurrencyFormat().format(Double.parseDouble(model.get(property).toString()));  
	        }  
	    });  
	    //estimate.setSummaryFormat(NumberFormat.getFormat("0.00")); 
	    estimate.setSummaryType(SummaryType.SUM);  
	    estimate.setSummaryRenderer(new SummaryRenderer() {  
	        public String render(Number value, Map<String, Number> data) {  
	            return NumberFormat.getCurrencyFormat().format(value.doubleValue());  
	        }  
	   });  
	   estimate.setEditor(new CellEditor(new NumberField()));  
	   columns.add(estimate);  
	   
	   ColumnModel cm = new ColumnModel(columns);  
	   
	   GroupSummaryView summary = new GroupSummaryView();  
	   summary.setForceFit(true);  
	   summary.setShowGroupedColumn(false);  
	   
	   grid = new EditorGrid<BusiObject>(getGroupStore(), cm);  
	   grid.setBorders(true);  
	   grid.setView(summary);  
	   grid.getView().setShowDirtyCells(false);
	   grid.setSize(920,350);
	   return grid ;
	}
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	MessageBox boxysn = new MessageBox();
	MessageBox costBox = new MessageBox();
	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							 if(be.getSource().equals(btnAdd)){
								 String month = DateTimeFormat.getFormat("yyyy-MM").format(dfAdd.getValue());
								 
								 if(!dfAdd.getRawValue().equals("") && !bcb.getRawValue().equals("")&& !tfNum.getRawValue().equals("") && !nfMoney.getRawValue().equals("")){
									 String sqls = "select * from hr_salary_ext where code='D02' and convert(varchar(7),adddate,120)='"+month+"' and others = '" + tfNum.getRawValue() + "'";
									 final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
										greetingService2.getDataSet(sqls, new AsyncCallback<DataSet>(){
											@Override
											public void onFailure(Throwable caught) {
												
											}
											@Override
											 public void onSuccess(DataSet result) {
												 if(result.getRowCount() > 0){
													 costBox.show();  
												 }else{
													 add();
												 }
											 }
										});	   
									}else{
										MessageBox.alert("警告",	"录入的信息不完整,请填写完整!", null);
										return;
									}
							 }else if(be.getSource().equals(btnQuery)){
								 String sql = " select icode,code,ROUND(amount,2) as amount,adddate,bcode,createdate,createbcode,others from hr_salary_ext  where (code='D02' or code='D01')";
								 
								 if (dfQuery.getValue() == null && tx.getRawValue().equals("")&&bcb2.getRawValue().equals("")) {
									 MessageBox.alert("提示", "请输入查询条件，谢谢！", null);
									 return;
								 }
								 
								 if (!dfQuery.getRawValue().equals("")) {
										DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");
										searchDate = dtf.format(dfQuery.getValue());
										sql += " and datediff(month,'"
												+ searchDate
												+ "',adddate )=0 ";

											 
									 
								 } else {
									 searchDate = "0";
								 }
								 
								 if (!tx.getRawValue().equals("")) {
									 hostel = tx.getRawValue();
						//			 sql += " and exists (select * from hr_hostel_bcode where bcode = hr_salary_ext.bcode and code ='" + hostel + "')";
									 sql += " and others = '" + hostel + "'";
									System.out.println("sql==========" + sql);
								 } else {
									 hostel = "0";
								 }
								 
								 if (bcb2.getValue() != null) {
									 type = bcb2.getValue().get("code");
									 sql += " and code = '" + type + "'";
								 } else {
									 type = "0";
								 }
								 
								 getEmployeeChange(sql);
							 }else if(be.getSource().equals(btnMake)){
								 if(dfMake.getValue() == null){
									 MessageBox.alert("提示", "计算的条件填写不完整！", null);
									 return;
								 }else{
									 String sqls = "select * from hr_salary_ext where code='D01' and convert(varchar(7),adddate,120)='"+dfMake.getRawValue()+"'";
									 System.out.println("----->"+sqls);
									 final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
										greetingService2.getDataSet(sqls, new AsyncCallback<DataSet>(){
											@Override
											public void onFailure(Throwable caught) {
												
											}
											@Override
											 public void onSuccess(DataSet result) {
												 if(result.getRowCount() > 0){
													 	boxysn.setButtons("");
														boxysn.setButtons(MessageBox.YESNO);  
														boxysn.setIcon(MessageBox.QUESTION);  
														boxysn.setTitle("是否生成数据？");  
														boxysn.addCallback(new Listener<MessageBoxEvent> (){
															@Override
															public void handleEvent(MessageBoxEvent be) {
																if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){
																	String date = DateTimeFormat.getFormat("yyyy-MM").format(dfMake.getValue());
																	String delete = "delete from hr_salary_ext where code='D01' and convert(varchar(7),adddate,120)='"+date+"'";
																	Number money = hotelMoney.getValue();
																	make(money, date, delete);
																}
															}
														});  
														boxysn.setMessage("当前月份已生成宿舍扣费，重新生成将清除老记录，您确认重新生成吗？是 则删除当月'系统生成'的，再生成,否 则不做操作。");  
														boxysn.show();  
												 }else{
													 String date = DateTimeFormat.getFormat("yyyy-MM").format(dfMake.getValue());
													 Number money = hotelMoney.getValue();
													 make(money, date, "");
												 }
											 }
										});	   
								 }
							 }
						}else if (be.getType() == Events.Change) {
							if(be.getSource().equals(tfNum)){
								if(tfNum.getRawValue() != ""){
									String code=tfNum.getRawValue().toUpperCase();
									String sql="select code from hr_Hostel where code='"+code+"'";
									final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
									greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
										@Override
										public void onFailure(Throwable caught) {
											
										}
										@Override
										 public void onSuccess(DataSet result) {
											 if(result.getRowCount()<1){
												 MessageBox.alert("警告",	"找不到改宿舍的号码,请确认是否填写有误!", null);
												 tfNum.setValue("");
												 tfNum.focus();
												 return;
											 }
										 }
									});	   
								}
							}
						}else if (be.getType() == Events.KeyPress){
							if (be.getSource().equals(nfMoney)) {
								if (((ComponentEvent) be).getKeyCode() == 13|| ((ComponentEvent) be).getKeyCode() == 10 ){
									btnAdd.focus();
								}
							
							}
						}
					}
				}
				 finally {
					sync--;
				}
			}
		};
		return defaultlistener;
	}
	
	public void add() {
		add("");
	}
	
	public void add(String deleteSql){
		/*String date = DateTimeFormat.getFormat("yyyy-MM-dd").format(dfAdd.getValue());
		String type = bcb.getValueCode();
		final String hostelcodestr =tfNum.getValue();
		double amount_setstr = nfMoney.getValue().doubleValue();
		
		if (date.equals("") || type.equals("") || hostelcodestr.equals("") || amount_setstr == 0) {
			MessageBox.alert("提示", "请输入完整的添加信息再进行添加操作，谢谢", null);
			return;
		}
		
		String sql = "insert into  hr_salary_ext (code,multiple,createbcode,createdate,adddate,bcode,others,amount) ";
        sql +=  "select '"+type+"' as code,1 as multiple,'"+Env.getEnvbcode()+"'as createbcode,convert(char(10),GetDate(),120) as createdate,'"+date+"' " +
        		"as adddate,  bcode ,'"+hostelcodestr+"' as others,(select case when count(*) =0 then 0 else "+amount_setstr+"/count(*) " +
        		"end as amount from hr_hostel_bcode where code = '"+hostelcodestr+"' and livedate <'"+date+"' and (leavedate is null or leavedate >='" + date + "') group by code ) as amount " +
        		"from hr_hostel_bcode where  code = '"+hostelcodestr+"' and livedate <'"+date+"' and (leavedate is null or leavedate >='" + date + "')";
        //发生日期一般都选为有新员工入住的日期或有员工退宿的日期，所以在结算水电费时，只能结算入住日期小于
        //发生日期（因为刚入住，自己不然用小于等于，如果小于等于，就把刚住进来的人给算进去了）
        //并且退宿日期大于等于发生日期的员工的水电费
         * 
         * 用于宿舍员工每有变动都计算宿舍费的情况。
         */
		final String date = DateTimeFormat.getFormat("yyyy-MM-dd").format(dfAdd.getValue());
		String month = DateTimeFormat.getFormat("yyyy-MM").format(dfAdd.getValue());
		String type = bcb.getValueCode();
		final String hostelcodestr =tfNum.getValue();
		double amount_setstr = nfMoney.getValue().doubleValue();
		
		if (month.equals("") || type.equals("") || hostelcodestr.equals("") || amount_setstr == 0) {
			MessageBox.alert("提示", "请输入完整的添加信息再进行添加操作，谢谢", null);
			return;
		}
		
		String sql = "insert into  hr_salary_ext (code,multiple,createbcode,createdate,adddate,bcode,others,amount) ";
        sql +=  "select '"+type+"' as code,1 as multiple,'"+Env.getEnvbcode()+"'as createbcode,convert(char(10),GetDate(),120) as createdate,'"+date+"' " +
        		"as adddate,  bcode ,'"+hostelcodestr+"' as others,(select case when count(*) =0 then 0 else "+amount_setstr+"*1.0/count(*) " +
        		"end as amount from hr_hostel_bcode where code = '"+hostelcodestr+"' and convert(varchar(7), livedate, 120) <='"+month+"' and (leavedate is null or convert(varchar(7), leavedate, 120) >='" + month + "') group by code ) as amount " +
        		"from hr_hostel_bcode where  code = '"+hostelcodestr+"' and convert(varchar(7), livedate, 120) <='"+month+"' and (leavedate is null or convert(varchar(7), leavedate, 120) >='" + month + "')";
        //只有在这个月入住的或者离宿的，不管住了一天，都平分钱，然后让HR自己去修改
        
        CommandSyncsql csql = new CommandSyncsql();
        
        if (!deleteSql.equals("")) {
        	csql.getV().add(deleteSql);
        }
        csql.getV().add(sql);
        CommandSyncContainer list = new CommandSyncContainer();
		list.add(csql);
		
		GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
		greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("错误","网络连接失败", null);
			}
			@Override
			public void onSuccess(CommandSyncReturnObject result) {
				if (result.isB()) {
					Info.display("", "添加成功");
					String date = DateTimeFormat.getFormat("yyyy-MM-dd").format(dfAdd.getValue());
					String sql = "select  icode,code,ROUND(amount,2) as amount,adddate,bcode,createdate,createbcode,others  from hr_salary_ext where code='D02' and others = '" + hostelcodestr + "' and adddate='"+date+"'";
					getEmployeeChange(sql);
				}else{
					MessageBox.alert("错误","错误，错误代码"+result.getMessage(), null);
				}
			}
		});
	}
	
	public void make(Number number, final String month, String deleteSql){
		String date = DateTimeFormat.getFormat("yyyy-MM").format(dfMake.getValue());
		String[] dates = date.split("-");
		int days = days(Integer.parseInt(dates[0]),Integer.parseInt(dates[1]));
		date += "-"+days;
		String sql = "insert into  hr_salary_ext (code,multiple,createbcode,createdate,adddate,bcode,others,amount,maketype) ";
        sql +=  "select 'D01' as code,1 as multiple,'"+Env.getEnvbcode()+"' as createbcode,convert(char(10),GetDate(),120) as createdate,'"+date+"' as adddate,bcode ," +
        		"code as others,"+number+" as amount,'系统生成' as maketype from hr_hostel_bcode a where exists (select 1 from hr_hostel_bcode, bcode_job where convert(varchar(7),livedate,120) <= '" + 
        		month + "' and (leavedate is null or convert(varchar(7),leavedate,120) >= '" + month + "') and bcode_job.bcode = hr_hostel_bcode.bcode and isCount = 1 group by hr_hostel_bcode.bcode having max(hr_hostel_bcode.icode) = a.icode)";
        //需要交宿舍费的人就是在生效月份之前或生效月份入职的并且退宿日期大于等于生效月份（这个是为了防止员工已经退宿，但是在交完宿舍费后才填写的退宿日期，下面的delete
        //语句没有delete到的数据的）的；
        
        CommandSyncsql csql = new CommandSyncsql();
        if (!deleteSql.equals("")) {
        	csql.getV().add(deleteSql);
        }
        csql.getV().add(sql);
        
        CommandSyncContainer list = new CommandSyncContainer();
		list.add(csql);
		
		GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
		greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("错误","网络连接失败", null);
			}
			@Override
			public void onSuccess(CommandSyncReturnObject result) {
				if (result.isB()) {
					String sql = "select  icode,code,ROUND(amount,2) as amount,adddate,bcode,createdate,createbcode,others  from hr_salary_ext where code='D01' and convert(varchar(7),adddate,120)='"+month+"'";
					Info.display("提示", "宿舍费用生成，请查询");
					getEmployeeChange(sql);
					/*String deleteStaff = "delete hr_hostel_bcode where convert(varchar(7),leavedate,120) <= '" + month + "'";
					//删除所有的已经退宿，并且退宿日期小于等于发生月份的数据；
					CommandSyncsql csql = new CommandSyncsql();
					csql.getV().add(deleteStaff);
					CommandSyncContainer list = new CommandSyncContainer();
					list.add(csql);
					GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
					greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误","网络连接失败", null);
						}
						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							Info.display("", "成功生成记录，并且已把在" + month + "月（包括这个月）之前的退宿员工的记录删除");
						}
					});*/
				}else{
					MessageBox.alert("错误","错误，错误代码"+result.getMessage(), null);
				}
			}
		});
	}
	
	public static int days(int year, int month) {
		int days = 0;
		if (month != 2) {
			switch (month) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				days = 31;
				break;
			case 4:
			case 6:
			case 9:
			case 11:
				days = 30;
			}
		} else {
			if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
				days = 29;
			else
				days = 28;
		}
		return days;
	}
	
	private boolean commandSql(String sql) {
		CommandSyncsql csql = new CommandSyncsql();// 执行sql命令
		String delsql = sql;
		csql.getV().add(delsql);
		if (csql.getV().size() <= 0) {
			return false;
		} else {
			CommandSyncContainer list = new CommandSyncContainer();// 可以添加的命令
			list.add(csql);

			GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
			greetingService.SendCommandSync(list,new AsyncCallback<CommandSyncReturnObject>() {
				@Override
				public void onFailure(Throwable caught) {
					MessageBox.alert("错误", "网络连接失败", null);
				}

				@Override
				public void onSuccess(CommandSyncReturnObject result) {
					if (result.isB()) {
						Info.display("提示信息", "生成数据成功");
					} else {
						MessageBox.alert("错误", "错误，错误代码"+ result.getMessage(), null);
					}
				}
			});
		}
		return true;
	}
}